package utils

import (
	"bufio"
	"io"
	"io/ioutil"

	// "log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

//下载文件
func DownFile(url string) []byte {
	client := http.Client{Timeout: 900 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		Log.Debug("打开url失败", err)
		return []byte{}
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		Log.Debug("读取下载数据失败", err)
		return []byte{}
	}
	return body
}

//获取文件列表
type FilesList struct {
	FileList []FileListStruct
}

type FileListStruct struct {
	Name string
	Type string
	Size string
	Time string
	Url  string
}

func (fl *FilesList) GetFileList(url []string) {

	fileType := map[string][]string{ //根据拓展名定义文件类型
		"picture": {"jpg", "jpeg", "gif", "png", "bmp"},
		"video":   {"mp4", "3gp", "avi", "flv", "wmv", "mkv"},
		"btfile":  {"torrent"},
		"audio":   {"mp3"},
		"other":   {"mpg", "rmvb", "rm", "vob", "mov"},
	}
	sdirs := url
	// filesLists := []FileListStruct{} //存放retrun列表
	for len(sdirs) != 0 { //判断文件夹列表内是否有数据
		sdir := sdirs[0]                                    //获取第一个数据
		sdirs = sdirs[1:]                                   //将获取的数据清除
		if sdir[len(sdir)-1:] != string(os.PathSeparator) { //判断获取的文件夹后面是否有/
			sdir = sdir + string(os.PathSeparator) //如果没有，添加/
		}
		files, _ := ioutil.ReadDir(sdir) //获取目录内的文件和文件夹
		for _, f := range files {        //迭代获取到的内容
			if f.IsDir() { //判断是否为文件夹
				// var dirlist DirsList //定义一个文件类型
				// dirlist.Name = f.Name()
				dirtmp, _ := filepath.Abs(sdir + f.Name()) //获取绝对路径
				sdirs = append(sdirs, dirtmp)
			} else {
				var filelist FileListStruct
				filelist.Name = f.Name()
				filetzm := filepath.Ext(filelist.Name)
				if filetzm != "" {
					filetzm = strings.ToLower(filetzm[1:])
					// fmt.Println("filetzm", filetzm)
					var t string
					for ts, key := range fileType {
						for _, t = range key {
							// fmt.Println("t", t, "tzm", filetzm)
							if t == filetzm {
								filelist.Type = ts
								break
							}

						}
						if t == "" {
							break
						}
					}
					dirtmp, _ := filepath.Abs(sdir)
					filelist.Url = dirtmp + string(os.PathSeparator)
					filelist.Size = strconv.FormatInt(f.Size(), 10)
					fl.FileList = append(fl.FileList, filelist)
				}

			}
		}
	}
}

//复制文件
func CopyFile(srcName, dstName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		Log.Debug("打开源文件错误", err)
		return
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644) //写入模式，或者创建，权限0644
	if err != nil {
		Log.Debug("打开目的文件错误", err)
		return
	}
	defer dst.Close()
	return io.Copy(dst, src)
}

//读取配置文件
//`
//读取配置文件代码来源
//https://studygolang.com/articles/4300
//作者：u014798316
//`
type Config struct {
	Mymap  map[string]string
	strcet string
}

func (c *Config) InitConfig(path string) {
	c.Mymap = make(map[string]string)

	f, err := os.Open(path)
	if err != nil {
		Log.Error("打开配置文件错误", err)
		return
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			Log.Error("读取配置文件错误", err)
			return
		}
		s := strings.TrimSpace(string(b))
		//fmt.Println(s)
		if strings.Index(s, "#") == 0 {
			continue
		}

		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		if len(c.strcet) == 0 {
			continue
		}
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}
		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		//		key := c.strcet + middle + frist
		key := c.strcet + frist
		c.Mymap[key] = strings.TrimSpace(second)
	}
}

func (c Config) Read(node, key string) string {
	//	key = node + middle + key
	key = node + key
	v, found := c.Mymap[key]
	if !found {
		return ""
	}
	return v
}

//	myConfig := new(cf.Config)
//	myConfig.InitConfig("config.ini")
//	mysqladdr := myConfig.Read("default", "ipaddr")
//	//	fmt.Printf("%v", myConfig.Mymap)
//	//	for v, a := range myConfig.Mymap {
//	//		fmt.Println(v, a)
//	//	}

//判断文件夹是否存在
func PathExists(path string, mkdir bool) (bool, error) {
	_, err := os.Stat(path)
	dirStute := false
	if err == nil { //如果返回的错误为nil,说明文件或文件夹存在
		dirStute = true
	}
	if os.IsNotExist(err) { //如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
		dirStute = false
	}
	if mkdir && !dirStute { //如果mkdir为True，则创建文件夹
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			Log.Error("创建文件失败", err)
		}
		dirStute = true
		return dirStute, err
	}
	return dirStute, err //如果返回的错误为其它类型,则不确定是否在存在
}
